package org.csu.jpetstore_users_backend_pj.service.impl;

import org.csu.jpetstore_users_backend_pj.entity.Cart;
import org.csu.jpetstore_users_backend_pj.mapper.CartMapper;
import org.csu.jpetstore_users_backend_pj.service.CartService;
import org.csu.jpetstore_users_backend_pj.service.CatalogService;
import org.csu.jpetstore_users_backend_pj.vo.CartItemVO;
import org.csu.jpetstore_users_backend_pj.vo.CartVO;
import org.csu.jpetstore_users_backend_pj.vo.ItemVO;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("cartService")
@MapperScan("org.csu.petstore.mapper")
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CatalogService catalogService;
    @Override
    public void insertCart(String userid, CartVO cartVO) {
        //String itemId = "";
        try {
            String cartInfo = "";
            for (CartItemVO cartitem : cartVO.getCartItemList()){
                cartInfo+= cartitem.getItem().getItemId() + " " + String.valueOf(cartitem.getQuantity()) + " ";
            }

            cartMapper.insert(new Cart(userid,cartInfo));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateCArtInfo(String userid, CartVO cartVO) {
        try {
            String cartInfo = "";
            for (CartItemVO cartitem : cartVO.getCartItemList()){
                cartInfo+= cartitem.getItem().getItemId() + " " + String.valueOf(cartitem.getQuantity()) + " ";
            }

            cartMapper.updateById(new Cart(userid,cartInfo));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean checkCartByUserId(String userid) {
        return cartMapper.selectById(userid)!=null;
    }

    @Override
    public CartVO getCartByCartInfo(String cartInfo){
        if(cartInfo==null||cartInfo.equals(""))
        {
            return null;
        }
        else{

            String[] parts = cartInfo.split(" ");

            // 创建一个Map用于保存id和数量的对应关系
            Map<String, Integer> idQuantityMap = new HashMap<>();

            // 使用循环遍历分割后的字符串数组
            for (int i = 0; i < parts.length; i += 2) {
                String id = parts[i]; // 获取当前位置的id
                int quantity = Integer.parseInt(parts[i + 1]); // 获取当前位置的数量并转为整数

                // 将id和对应的数量保存到Map中
                idQuantityMap.put(id, quantity);
            }

            CartVO cartVO  = new CartVO();
            for (Map.Entry<String, Integer> entry : idQuantityMap.entrySet()) {
                String id = entry.getKey();
                int quantity = entry.getValue();
                boolean isInStock = catalogService.isItemInStock(id);
                ItemVO itemVO = catalogService.getItem(id);
                cartVO.addItem(itemVO, isInStock);
                cartVO.setQuantityByItemId(id,quantity);
            }
//            System.out.println("-------------"+cartVO.getCartItemList().toString());
            return cartVO;
        }
    }
    @Override
    public CartVO getCart(String userid) {
        String cartInfo="";
        Cart cart=cartMapper.selectById(userid);
        if(cart==null) {
            //第一次启动购物车，在数据库建表，再次获取
            cartMapper.insert(new Cart(userid, ""));
            cart=cartMapper.selectById(userid);
        }
        cartInfo=cart.getCartinfo();
        if(cartInfo==null||cartInfo.equals(""))
        {
            return null;
        }
        else{

            String[] parts = cartInfo.split(" ");

            // 创建一个Map用于保存id和数量的对应关系
            Map<String, Integer> idQuantityMap = new HashMap<>();

            // 使用循环遍历分割后的字符串数组
            for (int i = 0; i < parts.length; i += 2) {
                String id = parts[i]; // 获取当前位置的id
                int quantity = Integer.parseInt(parts[i + 1]); // 获取当前位置的数量并转为整数

                // 将id和对应的数量保存到Map中
                idQuantityMap.put(id, quantity);
            }

            CartVO cartVO  = new CartVO();
            for (Map.Entry<String, Integer> entry : idQuantityMap.entrySet()) {
                String id = entry.getKey();
                System.out.println("id:"+id);
                int quantity = entry.getValue();
                boolean isInStock = catalogService.isItemInStock(id);
                ItemVO itemVO = catalogService.getItem(id);
                cartVO.addItem(itemVO, isInStock);
                cartVO.setQuantityByItemId(id,quantity);
            }
            return cartVO;
        }

    }

    @Override
    public void updateCartInfo(String userid, String itemId, String quantity) {
        String cartInfo="";
            //String sql = "SELECT cartinfo FROM carts WHERE userid = ?";
        Cart cart=cartMapper.selectById(userid);
        if(cart!=null){
            cartInfo=cart.getCartinfo();
        }

        String[] words = cartInfo.split("\\s+"); // 以空格分割字符串

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(itemId) && i + 1 < words.length) {
                words[i + 1] = quantity; // 替换itemId后面的单词
                break;
            }
        }

        cartInfo = String.join(" ",words);

        //String UPDATECARTINFO = "UPDATE carts " + "SET cartinfo = '" + cartInfo + "'" + " WHERE userid = '" + userid + "'";

        cartMapper.updateById(new Cart(userid,cartInfo));

    }

    @Override
    public void clearCart(String username) {
        cartMapper.updateById(new Cart(username,""));
    }
}
